#pragma once

#include "util.hpp"
#include <mutex>
#include <unordered_map>

using ws_server_t = websocketpp::server<websocketpp::config::asio>;
class online_user_manager
{
public:
    void enter_game_hall(int uid, ws_server_t::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.emplace(uid, conn);
    }
    void enter_game_room(int uid, ws_server_t::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.emplace(uid, conn);
    }
    void exit_game_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.erase(uid);
    }
    void exit_game_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.erase(uid);
    }
    bool is_in_game_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto iter = _hall_user.find(uid);
        if(iter == _hall_user.end()) return false;
        return true;
    }

    bool is_in_game_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto iter = _room_user.find(uid);
        if(iter == _room_user.end()) return false;
        return true;
    }

    ws_server_t::connection_ptr get_conn_from_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto iter = _hall_user.find(uid);
        if(iter == _hall_user.end()) return ws_server_t::connection_ptr();
        return iter->second;
    }

    ws_server_t::connection_ptr get_conn_from_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto iter = _room_user.find(uid);
        if(iter == _room_user.end()) return ws_server_t::connection_ptr();
        return iter->second;
    }

    std::vector<int> get_hall_usrid()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        std::vector<int> res;
        for(auto &[key,value] : _hall_user) {
            res.emplace_back(key);
        }
        return res;
    }

private:
    // 都是user_id与连结的对应关系
    std::unordered_map<int, ws_server_t::connection_ptr> _hall_user;
    std::unordered_map<int, ws_server_t::connection_ptr> _room_user;
    std::mutex _mutex;
};